//package com.jeffdouglas;
 package SendBoth;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
 
import com.sforce.ws.*;
import com.sforce.ws.bind.XmlObject;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.sobject.SObject;
 
public class SendTweetServlet extends HttpServlet {
 
  private static final Logger log = Logger.getLogger(SendTweetServlet.class);
 
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
 
    PartnerConnection connection = null;
    String feedPost = null;
 
    try {
      if (connection == null) {
        ConnectorConfig config = new ConnectorConfig();
        config.setUsername(Credentials.SFDC_USERNAME);
        config.setPassword(Credentials.SFDC_PASSWORD);
        connection = Connector.newConnection(config);
      }
 
      QueryResult results = connection
          .query("SELECT Id, FeedPost.Body FROM UserFeed WHERE "
              + "ParentId = '" + Credentials.SFDC_USERID + "'"
              + " And Type = 'UserStatus' ORDER BY CreatedDate DESC LIMIT 1");
 
      // in this case there will only be 1 record returned, but....
      for (int i = 0; i < results.getRecords().length; i++) {
        SObject feed = results.getRecords()[i];
        feedPost = getFeedBody(feed);
      }
 
    } catch (ConnectionException ce) {
      log.error(ce.toString());
    }
 
    if (feedPost != null) {
      sendTweet(feedPost, req, resp);
      resp.getWriter().println("Chatter message sent to Twitter: " + feedPost);
    } else {
      resp.getWriter().println("Nothing sent to Twitter");
    }
 
  }
 
  private void sendTweet(String tweet, HttpServletRequest req, HttpServletResponse resp) {
 
    HttpSession session = req.getSession();
    Twitter twitter = new TwitterFactory().getInstance();
 
    twitter.setOAuthConsumer(Credentials.TWITTER_CONSUMERKEY,
        Credentials.TWITTER_CONSUMERSECRET);
 
    // if the access token is present in the session
    if (session.getAttribute("accessToken") == null){
        // get the request token from the session
        String token = (String) session.getAttribute("token");
        String tokenSecret = (String)session.getAttribute("tokenSecret");
 
        // get the access token from twitter
        AccessToken accessToken = null;
        try {
          accessToken = twitter.getOAuthAccessToken(token, tokenSecret);
        } catch (TwitterException e) {
          log.error(e.toString());
        }
        twitter.setOAuthAccessToken(accessToken);
 
        // save the access token, that are different from request token
        session.setAttribute("accessToken", accessToken.getToken());
        session.setAttribute("accessTokenSecret", accessToken.getTokenSecret());
 
    } else {
        // use the access token from the session
        twitter.setOAuthAccessToken((String)session.getAttribute("accessToken"),
            (String)session.getAttribute("accessTokenSecret"));
    }
 
    try {
      // update the user's twitter status
      twitter.updateStatus(tweet);
    } catch (TwitterException e) {
      log.error(e.toString());
    }
 
  }
 
  private String getFeedBody(SObject feed) {
    String feedBody = "";
    Iterator<xmlObject> feedPost = feed.getChildren();
    while (feedPost.hasNext()) {
      XmlObject post = feedPost.next();
      if (post.getValue() == null) {
        Iterator<xmlObject> body = post.getChildren();
        while (body.hasNext()) {
          XmlObject child = body.next();
          if (child.getName().toString().equals(
              "{urn:sobject.partner.soap.sforce.com}Body")) {
            feedBody = child.getValue().toString();
            break;
          }
        }
      }
    }
    return feedBody;
  }
}